package com.explorati.design_pattern.structural.proxy.cglib;

import java.lang.reflect.Method;

import com.explorati.design_pattern.structural.proxy.Order;
import com.explorati.design_pattern.structural.proxy.db.DataSourceContextHolder;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class CglibProxy implements MethodInterceptor {

	private Object target;

	public CglibProxy(Object target) {
		this.target = target;
	}

	public Object getProxy() {
		Enhancer e = new Enhancer();
		e.setSuperclass(target.getClass());
		e.setCallback(this);
		return e.create();
	}

	@Override
	public Object intercept(Object proxy, Method mehod, Object[] args, MethodProxy methodProxy) throws Throwable {

		Object argObject = args[0];
		beforeMethod(argObject);

		Object result = methodProxy.invoke(target, args);

		afterMethod();
		return result;
	}

	private void beforeMethod(Object obj) {
		int userId = 0;
		System.out.println("Cglib代理 before code");
		if (obj instanceof Order) {
			Order order = (Order) obj;
			userId = order.getUserId();
		}
		int dbRouter = userId % 2;
		System.out.println("Cglib代理分配到 【db" + dbRouter + "】处理数据");

		// todo 设置dataSource;
		DataSourceContextHolder.setDBType(String.valueOf(dbRouter));
	}

	public void afterMethod() {
		System.out.println("Cglib代理after code");
	}

}
